#include "widget.h"
#include "ui_widget.h"
#include "cpage.h"
#include "cupdatedialog.h"

#include <QFileDialog>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    qDebug() << QSqlDatabase::drivers();

    auto db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("yhdn.cn");
    db.setUserName("admin");
    db.setPassword("Stallman7*");
    db.setDatabaseName("world");
    if(!db.open()){
        qDebug() << db.lastError().text();
        return;
    }

    mypage = new CPage("city",db,this);
    //信号和槽
    connect(ui->m_btn_first,SIGNAL(clicked()),this,SLOT(doBtnCommand()));
    connect(ui->m_btn_last,SIGNAL(clicked()),this,SLOT(doBtnCommand()));
    connect(ui->m_btn_next,SIGNAL(clicked()),this,SLOT(doBtnCommand()));
    connect(ui->m_btn_prev,SIGNAL(clicked()),this,SLOT(doBtnCommand()));
    connect(ui->m_btn_export,SIGNAL(clicked()),this,SLOT(doBtnCommand()));
    connect(ui->m_btn_sqlite,SIGNAL(clicked()),this,SLOT(doBtnCommand()));
    connect(ui->m_cbb_pagelist,SIGNAL(currentIndexChanged(int)),this,SLOT(doBtnCommand()));
    connect(ui->m_le_cur_page,SIGNAL(returnPressed()),this,SLOT(doBtnCommand()));
    connect(ui->m_le_search,SIGNAL(returnPressed()),this,SLOT(doBtnCommand()));
    connect(ui->m_btn_search,SIGNAL(clicked()),ui->m_le_search,SIGNAL(returnPressed()));

    connect(ui->m_view,&QTableView::doubleClicked,this,[=](const QModelIndex &index){

        if (!index.isValid())
            return ;

        auto model = (QSqlQueryModel*)index.model();
        auto record = model->record(index.row());

        //弹出对话框用于编辑
        CUpdateDialog dlg("city",record);
        auto returnCode = dlg.exec();
        if(returnCode){
            //修改成功
            mypage->refresh();
        }


    });


    connect(mypage,&CPage::searchFinished,this,[=](int totalPage,int curPage,int totalRecord){

        m_total_page = totalPage;
        qDebug() << m_total_page << "处理searchFinished信号";
        ui->m_le_cur_page->setText(QString::number(curPage));

        //设置按钮状态
        QList<QWidget*> ctrls{ui->m_btn_first,ui->m_btn_last,ui->m_btn_next,ui->m_btn_prev,ui->m_le_cur_page};
        foreach (auto item, ctrls) {
            item->setEnabled(true);
        }

        ui->m_btn_first->setDisabled(curPage == 1);
        ui->m_btn_prev->setDisabled(curPage == 1);
        ui->m_btn_next->setDisabled(curPage == totalPage);
        ui->m_btn_last->setDisabled(curPage == totalPage);

        //设置统计数据
        ui->m_lbl_info->setText(tr("共计%1条记录 分成%2页显示 每页条数:").arg(totalRecord).arg(totalPage));


    });


    //设置界面
    ui->m_view->setModel(mypage->model());
    ui->m_cbb_pagelist->addItems({"20","30","50"});

    //初始数据
    int pageSize = ui->m_cbb_pagelist->currentText().toInt();
    mypage->doSearch(m_cur_page,"",pageSize);

    //最大化
    this->setWindowState(Qt::WindowMaximized);
}

Widget::~Widget()
{
    delete ui;

}

void Widget::doBtnCommand()
{

    int pageSize = ui->m_cbb_pagelist->currentText().toInt();

    if (sender() == ui->m_btn_first ){

        m_cur_page = 1;

    }
    else if(sender() == ui->m_btn_last){
        m_cur_page = m_total_page;
    }
    else if(sender() == ui->m_btn_next){
        m_cur_page +=1;
    }
    else if(sender() == ui->m_btn_prev){
        m_cur_page -=1;
    }

    else if(sender() == ui->m_le_cur_page){
        m_cur_page = ui->m_le_cur_page->text().toInt();
    }
    else if(sender() == ui->m_le_search){
        m_cur_page = 1;
        m_keyword = ui->m_le_search->text();
    }
    else if(sender() == ui->m_cbb_pagelist){

    }
    else if(sender() == ui->m_btn_export){

        auto saveFile = QFileDialog::getSaveFileName(this,"保存为");
        if(!saveFile.isEmpty()){
            mypage->exportTable(saveFile);
            qDebug() << saveFile;

        }
        return;
    }
    else if(sender() == ui->m_btn_sqlite){


        QSqlDatabase _db = QSqlDatabase::addDatabase("QSQLITE","hello");

        do
        {
            //导出至sqlite数据库
            auto saveFile = QFileDialog::getSaveFileName(this,"保存为");
            if (saveFile.isEmpty())
                break;
            _db.setDatabaseName(saveFile);
            if(! _db.open())
                break;
            QString sql = "CREATE TABLE if not exists city"
                          "(id int primary key,"
                          "name text not null,"
                          "countrycode text not null unique,"
                          "District text not null,"
                          "population int not null)";

            //创建表格
            QSqlQuery query(_db);
            if (!query.exec(sql))
                break;


            //读取所有数据并保存
            auto model = (QSqlQueryModel*)ui->m_view->model();
            _db.transaction();

            for(int i=0;i<model->rowCount();i++){

                query.prepare("insert into city (id,name,countrycode,district,population) "
                              "values(:id,:name,:countrycode,district,population);");

                query.bindValue(":id",model->record(i).value("id").toInt());
                query.bindValue(":name",model->record(i).value("name").toString());
                query.bindValue(":countrycode",model->record(i).value("countrycode").toString());
                query.bindValue(":district",model->record(i).value("district").toString());
                query.bindValue(":population",model->record(i).value("population").toInt());

                query.exec();

            }

            _db.commit();


        }while(false);


        _db.close();

        return;
    }
    else
    {
        return ;
    }

    mypage->doSearch(m_cur_page,m_keyword,pageSize);


}
